package com.syq.play.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.syq.play.R;
import com.syq.play.adapter.ViewPagerAdapter;
import com.syq.play.lrc.LrcRead;
import com.syq.play.lrc.LyricContent;
import com.syq.play.lrc.LyricView;
import com.syq.play.service.IPlayer;
import com.syq.play.service.LocalService;
import com.syq.play.util.FileScanTool;
import com.syq.play.util.MyStringUtil;


import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class PlayActivity extends Activity implements OnClickListener{
	//UI
	private ViewPager vPager;
	private View viewIcon, viewLrc;
	private TextView tvRight, tvCtime, tvDtime, tvTitle;
	private ToggleButton tbPlay;
	private SeekBar seekBar;
	private LrcRead mLrcRead;
	private LyricView mLyricView;
	//DATA
	private Context context;
	private ViewPagerAdapter mainAdapter;
	private IPlayer mPlayer;
	
	private int index=0;
	
	private int CurrentTime=0;
	
	private int CountTime=0;
	private float mY=0;
	private int tempY=0;
	private boolean isRun=true, isShowLrc=false;
	
	private List<LyricContent> LyricList=new ArrayList<LyricContent>();
	private ServiceConnection mConnection = new ServiceConnection() { 
	    public void onServiceConnected(ComponentName className, IBinder service) { 
	        mPlayer = IPlayer.Stub.asInterface(service);
	    } 
	    public void onServiceDisconnected(ComponentName className) { 

	    }; 
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play);
		context=this;
		bindService(new Intent(context,  
                LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 
		initUi();
		setListener();
		mThread.start();
	}
	private void initUi(){
		tvTitle=(TextView)findViewById(R.id.tv_title);
		seekBar=(SeekBar)findViewById(R.id.seek_bar);
		tvCtime=(TextView)findViewById(R.id.tv_ctime);
		tvDtime=(TextView)findViewById(R.id.tv_dtime);
		tbPlay=(ToggleButton)findViewById(R.id.tb_play);
		tvRight=(TextView)findViewById(R.id.tv_right);
		tvRight.setText("歌词");
		tvRight.setVisibility(View.VISIBLE);
		vPager = (ViewPager) findViewById(R.id.vPager);
		mainAdapter = new ViewPagerAdapter(getListView());
		vPager.setAdapter(mainAdapter);
		vPager.setCurrentItem(0);
	}
	private void setListener(){
		findViewById(R.id.ll_left).setOnClickListener(this);
		findViewById(R.id.bt_next).setOnClickListener(this);
		findViewById(R.id.bt_prev).setOnClickListener(this);
		tvRight.setOnClickListener(this);
		vPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				switch(arg0){
				case 0:
					tvRight.setText("歌词");
					break;
				case 1:
					tvRight.setText("封面");
					break;
				}
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageScrollStateChanged(int arg0) {
				isRun=true;
			}
		});
		tbPlay.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					try {
						mPlayer.play();
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}else{
					try {
						mPlayer.pause();
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
		});
		seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			int p=0;
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				try {
					if(mPlayer!=null && mPlayer.isPrepare()){
						mPlayer.setCurrent(p);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if(fromUser){
					try {
						if(mPlayer!=null && mPlayer.isPrepare()){
							int DTime=mPlayer.getDuration();
							tvCtime.setText(MyStringUtil.formatLongToTimeStr((long)(DTime*progress/100)));
							p=DTime*progress/100;
						}
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.bt_next:
			toNext();
			break;
		case R.id.bt_prev:
			toPrev();
			break;
		case R.id.ll_left:
			finish();
			break;
		case R.id.tv_right:
			if("歌词".equals(tvRight.getText().toString())){
				tvRight.setText("封面");
				vPager.setCurrentItem(1);
			}else{
				tvRight.setText("歌词");
				vPager.setCurrentItem(0);
			}
			break;
		}
	}
	private List<View> getListView(){
		LayoutInflater mInflater=getLayoutInflater();
		List<View> listViews=new ArrayList<View>();
		View v1=(View)mInflater.inflate(R.layout.play_icon, null);
		View v2=(View)mInflater.inflate(R.layout.play_lrc, null);
		try {
			if(mPlayer!=null && mPlayer.isPrepare()){
				String path=mPlayer.getPath();
				if(path!=null && path.lastIndexOf("/")!=-1 && path.lastIndexOf(".")!=-1){
					String name=path.substring(path.lastIndexOf("/"), path.lastIndexOf("."));
					path="sdcard/Music/"+name+".lrc";
					Log.i("syq", "path="+path);
					if(FileScanTool.haveFile(path)){
						initLrc(v2, path);
						isShowLrc=true;
					}else{
						isShowLrc=false;
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		listViews.add(v1);
		listViews.add(v2);
		return listViews;
	}
	private Thread mThread=new Thread(){
		public void run() {
			try {
				for(;;){
					mHandler.sendMessage(new Message());
					Thread.sleep(100);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};
	};
	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				if(mPlayer!=null && mPlayer.isPrepare()){
					tbPlay.setClickable(true);
					tvTitle.setText(""+mPlayer.getTitle());
					long cTime=(long)mPlayer.getCurrentTime();
					long DTime=(long)mPlayer.getDuration();
					tvCtime.setText(MyStringUtil.formatLongToTimeStr(cTime));
					tvDtime.setText(MyStringUtil.formatLongToTimeStr(DTime));
					seekBar.setProgress((int)(cTime*100/DTime));
					if(mPlayer.isPlaying()){
						if(isRun && isShowLrc){
							mLyricView.SetIndex(Index());
							mLyricView.invalidate();
						}
						tbPlay.setChecked(true);
					}else{
						tbPlay.setChecked(false);
					}
				}else{
					tbPlay.setClickable(false);
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};
	@Override
	protected void onStart() {
		super.onStart();
	}
	@Override
	protected void onStop() {
		super.onStop();
		
	}
	private void initLrc(View v, String data){
		mLrcRead=new LrcRead();
		try {
//			mLrcRead.Read("sdcard/Music/"+name+".lrc");
			mLrcRead.Read(data);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
		LyricList=mLrcRead.GetLyricContent();
		
		if(mLyricView==null){
			mLyricView=(LyricView)v.findViewById(R.id.LyricShow);
			mLyricView.setOnTouchListener(new View.OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					final float eventY = event.getY();
					switch(event.getAction()){
					case MotionEvent.ACTION_DOWN:
						isRun=false;
						mY=eventY;
						break;
					case MotionEvent.ACTION_MOVE:
						int y=(int)((eventY-mY)/-1);
						 if(tempY!=y){
							tempY=y;
							Log.i("", "---------Y="+y);
							mLyricView.updateIndex(y);
							mLyricView.invalidate();
						}
						mY=eventY;
						break;
					case MotionEvent.ACTION_UP:
						try {
							if(mPlayer!=null && mPlayer.isPrepare()){
								mPlayer.setCurrent(LyricList.get(mLyricView.getIndex()).getLyricTime());
							}
							isRun=true;
						} catch (RemoteException e) {
							e.printStackTrace();
						}
						break;
					}
					return true;
				}
			});
		}
		//设置歌词资源
		mLyricView.setSentenceEntities(LyricList);
	}
	
	public int Index(){
        try {
			if(mPlayer.isPlaying()){
			 CurrentTime=mPlayer.getCurrentTime();
			 CountTime=mPlayer.getDuration();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		if(CurrentTime<CountTime){

			for(int i=0;i<LyricList.size();i++){
				if(i<LyricList.size()-1){
					if(CurrentTime<LyricList.get(i).getLyricTime()&&i==0){
						index=i;
						break;
					}

					if(CurrentTime>LyricList.get(i).getLyricTime()&&CurrentTime<LyricList.get(i+1).getLyricTime()){
						index=i;
						break;
					}
				}

				if(i==LyricList.size()-1&&CurrentTime>LyricList.get(i).getLyricTime()){
					index=i;
				}
			}
		}
		return index;
	}
	private void toPrev(){
		try {
			if(mPlayer!=null && mPlayer.isPrepare()){
				mPlayer.playPre();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	private void toNext(){
		try {
			if(mPlayer!=null && mPlayer.isPrepare()){
				mPlayer.playNext();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
//	private void setTitle(){
//        try {
//			if(mPlayer!=null && mPlayer.isPrepare()){
//				tvTitle.setText(""+mPlayer.getTitle());
//			}
//		} catch (RemoteException e) {
//			e.printStackTrace();
//		}
//	}
	
}
